#include "blockqueue.hpp"
#include <unistd.h>
#include <ctime>
#include "task.hpp"

pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *args)
{
    blockqueue<task> *bq = static_cast<blockqueue<task> *>(args);
    while (true)
    {
        task t = bq->pop();
        t.run();
        pthread_mutex_lock(&lock);
        std::cout << "完成了任务: " << t.show() << "result:" << t.Getresult() << "thread id: " << pthread_self() << std::endl;
        pthread_mutex_unlock(&lock);
    }
}
void *productor(void *args)
{
    blockqueue<task> *bq = static_cast<blockqueue<task> *>(args);

    while (true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10 + 1;
        int len = opers.size();
        char op = opers[rand() % len];
        // data++;
        task t(data1, data2, op);
        bq->push(t);
        pthread_mutex_lock(&lock);
        std::cout << "生产了任务: " << t.show() << "thread id: " << pthread_self() << std::endl;
        pthread_mutex_unlock(&lock);

        sleep(1);

        // sleep(1);
    }
}
int main()
{
    srand(time(nullptr));
    pthread_t c[3], p[5];
    blockqueue<task> *bq = new blockqueue<task>();
    for (int i = 0; i < 3; i++)
    {
        pthread_create(c + i, nullptr, consumer, bq);
    }
    for (int i = 0; i < 5; i++)
    {

        pthread_create(p + i, nullptr, productor, bq);
    }
    for (int i = 0; i < 3; i++)
    {

        pthread_join(c[i], nullptr);
    }
    for (int i = 0; i < 5; i++)
    {

        pthread_join(p[i], nullptr);
    }
    return 0;
}
// void *consumer(void *args)
// {
//     blockqueue<int> *bq = static_cast<blockqueue<int> *>(args);
//     while (true)
//     {
//         int number = bq->pop();
//         std::cout << "消费了数据: " << number << std::endl;
//     }
// }
// void *productor(void *args)
// {
//     blockqueue<int> *bq = static_cast<blockqueue<int> *>(args);
//     int data = 0;
//     while (true)
//     {
//         data++;
//         bq->push(data);
//         std::cout << "生产了数据: " << data << std::endl;
//         // sleep(1);
//     }
// }
// int main()
// {
//     pthread_t c, p;
//     blockqueue<int> *bq = new blockqueue<int>();
//     pthread_create(&c, nullptr, consumer, bq);
//     pthread_create(&p, nullptr, productor, bq);

//     pthread_join(c, nullptr);
//     pthread_join(p, nullptr);
//     return 0;
// }